package com.sikadwafastdaisfondturbo.pretloan.ui.credit.page

import android.annotation.SuppressLint
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.CreditAccountAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageCreditCommonBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.status.StatusRepository
import com.sikadwafastdaisfondturbo.pretloan.ui.launch.LaunchActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardAddDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardOnlyOneWarningDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardOtherDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.DataClearDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.SikadwaNoticeDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.SikadwaKefuConfigHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.SikadwaMainProcessHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.StarDialogHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import androidx.core.graphics.toColorInt
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：通用状态列表，包含：审核中、拒绝、放贷中、放贷中法语
 */
class CreditCommonPage(): ProFragment() {
    private var _binding: PageCreditCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot apply status binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var mCreditInfo: JSONObject? = null

    //账户列表
    private var mAccountAdapter: CreditAccountAdapter? = null

    //公告信息
    private var noticeDialog: SikadwaNoticeDialog? = null

    constructor(obj: JSONObject): this(){
        this.mCreditInfo = obj
    }

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageCreditCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        EventBus.getDefault().register(this)
        _binding?.parentLayout?.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        _binding?.contentLayout?.visibility = View.INVISIBLE

        initRefreshLayout()
        initRvAccount()

        _binding?.imgLang?.visibility = View.GONE
        if (Configs.isTanzania()){
            _binding?.imgLang?.visibility = View.VISIBLE
        }
    }

    override fun initListener() {
        _binding?.imgKefu?.setOnClickListener {
            mCreditInfo?.let {
                showKefuDialog(it.optString("eventRemark"))
                addEvent(EventType.CLICK.CLICK_CUSTOMER,it.optString("eventRemark"))
            }
        }
        //切换语言
        _binding?.imgLang?.setOnClickListener {
            mCreditInfo?.let {
                showSikadwaProLangDialog(it.optString("eventRemark"), onCheckSuccess = {

                })
            }
        }
        _binding?.imgUser?.setOnClickListener {
            mCreditInfo?.let {
                showPersonalDialog(it.optString("eventRemark"))
                addEvent(EventType.CLICK.CLICK_USER,it.optString("eventRemark"))
            }
        }
        //添加绑卡
        _binding?.addLayout?.setOnClickListener {
            showBindCardDialog()
        }
        //删除用户数据
        _binding?.dataClearLayout?.setOnClickListener {
            mCreditInfo?.let {
                showSikadwaDataClearConfirmDialog(it.optString("eventRemark"))
            }
        }
    }

    override fun initData() {
        showLoading()
        loadCreditInfoAction()
        loadAccountListAction()

        mCreditInfo?.let {
            addEvent(EventType.PAGE.PAGE_CREDIT_COMMON_START,it.optString("eventRemark"))
        }
    }

    /**
     * 状态改变，需要刷新页面
     */
    fun refreshView(data: JSONObject){
        this.mCreditInfo = data
        loadCreditInfoAction()
        loadAccountListAction()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化账户列表
     */
    private fun initRvAccount() {
        _binding?.rvAccount?.setHasFixedSize(true)
        _binding?.rvAccount?.isNestedScrollingEnabled = false
        _binding?.rvAccount?.isFocusableInTouchMode = false //不需要焦点
        _binding?.rvAccount?.layoutManager = LinearLayoutManager(context)
//        val topDecoration = DensityUtils.dp2px(16f)
//        _binding?.rvApp.addItemDecoration(LinearDecoration(0,0,topDecoration,0))
        mAccountAdapter = CreditAccountAdapter(_binding?.rvAccount)
        _binding?.rvAccount?.adapter = mAccountAdapter
        _binding?.rvAccount?.itemAnimator = DefaultItemAnimator()
        mAccountAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            val item = mAccountAdapter?.getItem(position)
        })
    }

    /**
     * 审核中
     */
    private fun showAuditView(){
        _binding?.vStatusBg?.setBackgroundResource(R.drawable.credit_apply_audit_bg)
        _binding?.textSyatus?.text = requireContext().getString(R.string.credit_common_status_audit)
        _binding?.textSyatus?.setBackgroundResource(R.drawable.radius_fill_ff0059aa_10)
        _binding?.imgStatusIcon?.setImageResource(R.mipmap.img_credit_apply_audit_icon)

        _binding?.tipsLayout1?.visibility = View.VISIBLE
        _binding?.conseilsLayout?.visibility = View.GONE
        _binding?.accountLayout?.visibility = View.VISIBLE
        _binding?.textRejectedAgainApplyDate?.visibility = View.GONE

        //只有法语地区才需要添加账户按钮
        if (!Configs.isFrench()){
            _binding?.addLayout?.visibility = View.GONE
        }
        loadStarCommentAction()

        //审核中显示公告信息
        showSikadwaNoticeDialog()
    }

    /**
     * 已拒绝
     */
    private fun showFailedView(){
        _binding?.vStatusBg?.setBackgroundResource(R.drawable.credit_apply_failed_bg)
        _binding?.textSyatus?.text = requireContext().getString(R.string.credit_common_status_rejected)
        _binding?.textSyatus?.setBackgroundResource(R.drawable.radius_fill_fff07b66_10)
        _binding?.imgStatusIcon?.setImageResource(R.mipmap.img_credit_apply_failed_icon)

        //下次申请时间
        val againApplyDate = SikadwaMainProcessHelper.takeSikadwaMainProcessApplyAgainDate()
        val showText = String.format(getString(R.string.credit_common_status_rejected_again_apply_date),againApplyDate)
        val startIndex = showText.indexOf(againApplyDate)
        val dataSecuritySpannable = SpannableString(showText)
        dataSecuritySpannable.setSpan(ForegroundColorSpan("#FFF07B66".toColorInt()), startIndex, startIndex + againApplyDate.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
//        dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + againApplyDate.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textRejectedAgainApplyDate?.text = dataSecuritySpannable


        _binding?.tipsLayout1?.visibility = View.GONE
        _binding?.conseilsLayout?.visibility = View.GONE
        _binding?.accountLayout?.visibility = View.GONE
        _binding?.textRejectedAgainApplyDate?.visibility = View.VISIBLE

        // TODO: 此处需要调是否显示清除用户数据接口
        loadSikadwaUserDataClearAction(true)
    }

    /**
     * 放贷中
     */
    private fun showLendingView(){
        _binding?.vStatusBg?.setBackgroundResource(R.drawable.credit_apply_lending_bg)
        _binding?.textSyatus?.text = requireContext().getString(R.string.credit_common_status_lending)
        _binding?.textSyatus?.setBackgroundResource(R.drawable.radius_fill_ff43da84_10)
        _binding?.imgStatusIcon?.setImageResource(R.mipmap.img_credit_apply_lending_icon)

        _binding?.tipsLayout1?.visibility = View.VISIBLE
        _binding?.conseilsLayout?.visibility = View.VISIBLE
        _binding?.accountLayout?.visibility = View.VISIBLE
        _binding?.textRejectedAgainApplyDate?.visibility = View.GONE
        //只有法语地区才需要添加账户按钮
        if (!Configs.isFrench()){
            _binding?.conseilsLayout?.visibility = View.GONE
            _binding?.addLayout?.visibility = View.GONE
        }
        loadStarCommentAction()

        //放款中显示公告信息
        showSikadwaNoticeDialog()
    }

    /**
     * 只有一个账户提示添加绑卡
     */
    private fun showOnlyOneAccountAddDialog(){
        val dialog = BindCardOnlyOneWarningDialog(requireContext(),object : BindCardOnlyOneWarningDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnAddMore){
                    showBindCardDialog()
                }
            }
        })
        dialog.show()
    }

    /**
     * 添加绑卡dialog
     */
    private fun showBindCardDialog(){
        addEvent(EventType.CLICK.CLICK_USER_ACCOUNT_ADD,"CreditAuditFrench Page")
        val bindCardDialog = BindCardAddDialog(context,"CreditAuditFrench Page",object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                onAddBindCardAction(phoneNumber,typeObj.optString("value"),"NO")
            }
        })
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    fun showBingAccountOtherDialog(otherInfo: JSONObject?) {
        otherInfo?.let {
            val replaceDialog = BindCardOtherDialog(context,"CreditAuditFrench Page",object : BindCardOtherDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnConfirm){//添加
                        onAddBindCardAction(it.optString("walletMobile"),it.optString("value"), "YES")
                    }
                }
            })
            replaceDialog.show()
            replaceDialog.setBindAccountInfo(it)
        }
    }

    /**
     * 是否确认清除用户数据dialog
     */
    private fun showSikadwaDataClearConfirmDialog(eventRemark: String){
        val dialog = DataClearDialog(requireContext(),eventRemark,object : DataClearDialog.IDialogCallback{
            override fun onClick(view: View?) {
                showLoading()
                loadSikadwaUserDataClearAction(false)
            }
        })
        dialog.show()
    }

    /**
     * 审核中、放款中 根据配置显示公告Dialog
     */
    private fun showSikadwaNoticeDialog(){
        // 在后台线程检查条件，避免主线程阻塞
        if (!shouldShowNoticeDialog()) {
            return
        }

        // 确保在主线程执行 UI 操作
        if (!isFragmentActive()) {
            return
        }

        createAndShowNoticeDialog()
    }

    /**
     * 创建并显示通知对话框
     */
    private fun createAndShowNoticeDialog() {
        if (!isFragmentActive()) {
            return
        }

        val noticeInfo = SikadwaKefuConfigHelper.takeSikadwaKefuNoticeInfo() ?: return

        // 更新显示次数
        SikadwaKefuConfigHelper.showNoticeNum = SikadwaKefuConfigHelper.showNoticeNum + 1

        var eventRemark = ""
        mCreditInfo?.let {
            eventRemark = it.optString("eventRemark")
        }

        noticeDialog = SikadwaNoticeDialog(requireContext(), object : SikadwaNoticeDialog.IDialogCallback {
            override fun onClick(view: View?) {
                // 处理点击事件
            }
        })

        noticeDialog?.let { dialog ->
            // 最终检查后再显示
            if (isFragmentActive()) {
                dialog.setNoticeRemark(eventRemark)
                dialog.show()
                dialog.setNoticeTitle(noticeInfo.optString("noticeTitle"))
                dialog.setNoticeMsg(noticeInfo.optString("noticeText"))
            }
        }
    }

    /**
     * 检查是否应该显示通知对话框
     */
    private fun shouldShowNoticeDialog(): Boolean {
        if (!SikadwaKefuConfigHelper.isSikadwaShowNotice()) {
            return false
        }

        val noticeInfo = SikadwaKefuConfigHelper.takeSikadwaKefuNoticeInfo() ?: return false
        val showNum = noticeInfo.optInt("num", 1)
        val num = SikadwaKefuConfigHelper.showNoticeNum

        if (num >= showNum) {
            return false
        }
        // 检查对话框是否已经在显示
        if (noticeDialog?.isShowing == true) {
            return false
        }
        return true
    }

    /**
     * 检查 Fragment 是否处于活跃状态
     */
    private fun isFragmentActive(): Boolean {
        return isAdded &&
                !isDetached &&
                activity != null &&
                !requireActivity().isFinishing &&
                !requireActivity().isDestroyed
    }

    /**
     * 设置贷款信息
     */
    @SuppressLint("SetTextI18n")
    private fun setCreditDataInfo(obj: JSONObject){
        if (mCreditInfo == null){
            onIntent(LaunchActivity::class.java)
            return
        }

        _binding?.contentLayout?.visibility = View.VISIBLE
        _binding?.textAmount?.text = obj.optString("amount") + " " + obj.optString("currency")
        _binding?.textDays?.text = String.format(requireContext().getString(R.string.credit_apply_loan_term_days),obj.optString("days"))
        _binding?.dataClearLayout?.visibility = View.GONE

        //1、判断是否存在 订单状态
        mCreditInfo?.let {
            if (it.has("orderStatus")) {
                val orderStatus = it.optString("orderStatus")
                //待还款
//            if (StatusRepository(null, orderStatus).isRepayNow()) {
//                showRepayPage()
//                return
//            }
                //放款中
                if (StatusRepository(null, orderStatus).isDisbursing()) {
                    showLendingView()
                    return
                }
                //申请贷款被拒绝
                if (StatusRepository(null, orderStatus).isRejected()) {
                    showFailedView()
                    return
                }
            }

            //2、判断是否存在 贷款申请状态
            if (it.has("applyStatus")){
                val applyStatus = it.optString("applyStatus")
                //审核中
                if (StatusRepository(applyStatus).isReviewing()){
                    showAuditView()
                    return
                }
                //被拒绝
                if (StatusRepository(applyStatus).isRejected()){
                    showFailedView()
                    return
                }
            }
        }
    }

    /**
     * 设置绑定的账户列表
     */
    private fun setAccountList(accountList: ArrayList<JSONObject>){
        mAccountAdapter?.data = accountList

        /**
         * 法语审核中 && 只有一个账户  提示新增绑卡
         */
        if (Configs.isFrench()){
            mCreditInfo?.let {
                //申请状态
                val applyStatus = it.optString("applyStatus")
                //审核中 && 只有一个账户
                if (StatusRepository(applyStatus).isReviewing() && accountList.size <= 1){
                    showOnlyOneAccountAddDialog()
                }
            }
        }
    }

    /**
     * 获取贷款信息
     */
    private fun loadCreditInfoAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_APPLY)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    setCreditDataInfo(obj)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 获取账户已绑定的列表
     */
    private fun loadAccountListAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.ACCOUNT_LIST)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val array = data.optJSONArray("obj")
                array?.let {
                    if (it.length() > 0) {
                        val accountList = arrayListOf<JSONObject>()
                        for (i in 0..<it.length()){
                            accountList.add(it.optJSONObject(i))
                        }
                        setAccountList(accountList)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 获取评分配置
     */
    private fun loadStarCommentAction() {
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.STAR_COMMENT)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    StarDialogHelper.showStarDialog(requireContext(),it,true)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 添加绑定账户（法语）
     */
    fun onAddBindCardAction(mobile: String,walletChannel: String, bindFlag:String) {
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.ACCOUNT_ADD)
            put("walletMobile",mobile)
            put("walletMobileConfirm",mobile)
            put("walletChannel",walletChannel)
            put("addBindFlag",bindFlag)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj") ?: JSONObject()
                //刷新列表
                loadAccountListAction()

                // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                val addBindFlag = obj.optString("addBindFlag")
                if (addBindFlag == "YES") {
                    //需要提示绑定另一个渠道账户
                    var otherAccountInfo: JSONObject? = null

                    //用于从APP配置中获取（walletChannels）对应的信息
                    val channel = obj.optString("channel")
                    val commonData = JSONObject(Configs.getSPString(Configs.SPKEY.SIKADWA_COMMON))
                    val customize = commonData.optJSONObject("customize")
                    if (customize != null) {
                        val walletChannels = customize.optJSONArray("walletChannels")
                        if (walletChannels != null && walletChannels.length() > 0) {
                            for (i in 0..<walletChannels.length()) {
                                val item = walletChannels.optJSONObject(i)
                                if (channel == item.optString("value")) {
                                    otherAccountInfo = item
                                    break
                                }
                            }
                        }

                        // 只有非空的情况下才处理
                        if (otherAccountInfo != null) {
                            otherAccountInfo.put("walletMobile", mobile)
                            //提示绑定另一个渠道账户
                            showBingAccountOtherDialog(otherAccountInfo)
                            return
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取是否显示删除用户数据按钮
     */
    private fun loadSikadwaUserDataClearAction(isGetBtn: Boolean){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.USER_DATA_CLEAR)
        }
        if (isGetBtn){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                if (isGetBtn){
                    val obj = data.optJSONObject("obj")
                    if (obj != null){
                        val showDropButton = obj.optString("showDropButton","NO")
                        when(showDropButton == "YES"){
                            true -> {
                                _binding?.dataClearLayout?.visibility = View.VISIBLE
                            }
                            else -> {
                                _binding?.dataClearLayout?.visibility = View.GONE
                            }
                        }
                    }
                } else {
                    hideLoading()
                    //退出登录
                    onLoginOutAction()
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshProcess(event: String){
        when(event){
            Configs.Event.REQUEST_FINISH_FAILED -> {//请求失败
                hideLoading()
                _binding?.refreshLayout?.finishRefresh()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mCreditInfo?.let {
            addEvent(EventType.PAGE.PAGE_CREDIT_COMMON_END,it.optString("eventRemark"))

        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
        noticeDialog?.dismiss()
        noticeDialog = null
        _binding = null
    }
}